<template>
	<view class="box">
		<view class="text-1">付款</view>
		<view class="content">
			<view class="text-2">付款金额</view>
			<view class="input-box">
				<view>
					<text class="text-3">￥</text>
					<input @input="checkMoney($event)" v-model="money" class="input"
						placeholder-style="font-weight:500;font-size: 32rpx;color: #999999;" type="digit"
						placeholder="请输入金额" />
				</view>
			</view>
			<view class="text-4">付款方式：</view>
			<view class="img-box">
				<view class="item" :class="{'item-active':currenType==='alipay'}" @click="chosePay('alipay')">
					<image mode="aspectFit" src="../../static/alipay.png"></image>
					<view class="text-5">支付宝支付</view>
				</view>
				<view class="item" :class="{'item-active':currenType==='wechat'}" @click="chosePay('wechat')">
					<image mode="aspectFit" src="../../static/weixin.png"></image>
					<view class="text-5">微信支付</view>
				</view>
			</view>
			<view class="text-6" @click="toPay">立即付款</view>
		</view>
		<uni-popup type="center" ref="popup">
			<view class="loading">
				<image class="close" src="../../static/close.png" @click="$refs.popup.close()"></image>
				<image mode="aspectFit" style="width: 250rpx;height: 250rpx;" src="../../static/loading.png"></image>
				<view class="text-7">{{money}}</view>
				<view class="text-8">正在支付</view>
				<view class="text-8">请等待</view>
			</view>
		</uni-popup>
		<uni-popup type="center" ref="popup1">
			<div class="qrCode">
				<div style="margin-bottom: 40rpx;">{{currenType==='alipay'?'请使用支付宝扫码支付':'请使用微信扫码支付'}}</div>
				<image style="width: 300rpx;height: 300rpx;" v-if="imageData" :src="imageData"></image>
				<div v-else ref="qrCode" />
			</div>
		</uni-popup>
		<view class="pay-bg" v-if="show" @click="show=false">
		</view>
	</view>
</template>

<script>
	import QRCode from "qrcodejs2";
	import {
		formatDate
	} from "../../common/utils";
	export default {
		data() {
			return {
				money: '',
				currenType: 'wechat',
				qrCode: '',
				imageData: '',
				info: '',
				appId: 'wx1adc932f1508e2bc',
				openId: '',
				isWeiXin: true,
				orderNo: '',
				show: false
			}
		},
		onLoad(options) {
			this.info = options
			var ua = navigator.userAgent.toLowerCase();
			this.isWeiXin = ua.indexOf('micromessenger') != -1;
		},
		onHide() {
			this.money = ''
			this.$refs.popup.close()
		},
		onShow() {
			if (!this.isWeiXin) return
			this.openId = uni.getStorageSync('openId')
			if (!this.openId) {
				if (this.info.code) {
					uni.showLoading({
						title: '正在登录...',
						mask: true
					})
					this.$api.wxLogin({
						platform: "wechat",
						code: this.info.code
					}).then(res => {
						if (res.code === 1) {
							uni.setStorageSync('openId', res.data.thirdinfo.openid)
							this.openId = res.data.thirdinfo.openid
						} else {
							uni.showModal({
								title: '提示',
								content: '获取openId失败',
								showCancel: false
							})
						}
					}).finally(() => {
						uni.hideLoading()
					})
				} else {
					let currentUrl = encodeURIComponent(window.location.href)
					window.location.replace(
						'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + this.appId + '&' +
						'redirect_uri=' + currentUrl +
						'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect')
				}
			}
		},
		methods: {
			chosePay(type) {
				this.currenType = type
			},
			toPay() {
				let reg = /(^[1-9]{1}[0-9]*$)|(^[1-9]*\.[0-9]{1,2}$)|(^[0]{1}\.[0-9]{1,2}$)/;
				if (this.money === '' || this.money === 0 || this.money === undefined || this.money === null || this
					.money === '0' || this.money === '0.00' || this.money === '0.0') {
					uni.showModal({
						title: '提示',
						content: '需填写金额',
						showCancel: false
					})
				} else if (reg.test(this.money)) {
					if (this.currenType === 'wechat') {
						if (!this.isWeiXin) {
							uni.showModal({
								title: '提示',
								content: '请在微信内进行支付',
								showCancel: false
							})
							return
						}
						if (!this.openId) return
						this.$refs.popup.open()
						this.$api.createOrder({
							amount: this.money,
							paytype: this.currenType,
							method: 'mp',
							openid: this.openId,
							admin_id: this.info.admin_id || ''
						}).then(res => {
							if (res.code === 1) {
								// this.getQRCode(res.data.code_url)
								this.orderNo = res.data.order_sn
								this.onBridgeReady(res.data)
							} else {
								this.$refs.popup.close()
								uni.showModal({
									title: '提示',
									content: res.msg || '请求出错 请稍后重试',
									showCancel: false
								})
							}
						}).catch(() => {
							this.$refs.popup.close()
						})
					} else {
						this.$refs.popup.open()
						this.$api.createOrder({
							amount: this.money,
							paytype: this.currenType,
							admin_id: this.info.admin_id || ''
						}).then(res => {
							if (res.code === 1) {
								this.orderNo = res.data.order_sn
								let divForm = document.getElementsByTagName('divform')
								if (divForm.length) {
									document.body.removeChild(divForm[0])
								}
								const div = document.createElement('divform');
								div.innerHTML = res.data.content;
								document.body.appendChild(div);
								document.getElementById('alipay_submit').submit();
								uni.setStorageSync('storageInfo', {
									money: JSON.parse(JSON.stringify(this.money)),
									type: this.currenType,
									time: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
									orderNo: this.orderNo
								})
							} else {
								this.$refs.popup.close()
								uni.showModal({
									title: '提示',
									content: res.msg || '请求出错 请稍后重试',
									showCancel: false
								})
							}
						}).catch(() => {
							this.$refs.popup.close()
						})
					}
				} else {
					uni.showModal({
						title: '提示',
						content: '金额输入有误',
						showCancel: false
					})
				}
			},
			checkMoney(e) {
				let val = e.target.value.replace(/(^\s*)|(\s*$)/g, "")
				console.log(val);
				if (!val) {
					return ''
				}
				var reg = /[^\d.]/g
				// 只能是数字和小数点，不能是其他输入
				val = val.replace(reg, "")
				// // 保证第一位只能是数字，不能是点
				val = val.replace(/^\./g, "");
				// // 小数只能出现1位
				val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
				// // 小数点后面保留2位
				val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
				this.$nextTick(() => {
					this.money = val
				})
				return val
			},
			getQRCode(text) {
				this.$refs.popup1.open()
				if (this.qrCode) this.qrCode.clear()
				this.imageData = ''
				this.$nextTick(() => {
					this.$refs.qrCode.innerHTML = "";
					this.qrCode = new QRCode(this.$refs.qrCode, {
						text,
						width: 150, //canvas 画布的宽
						height: 150, //canvas 画布的高
						typeNumber: 8,
						colorDark: '#000000',
						// colorLight: 'red',
						correctLevel: QRCode.CorrectLevel.H // 二维码可辨识
					})
					let canvasobj = document.getElementsByTagName("canvas")[0]
					let img = this.CanvasToImage(canvasobj)
					this.imageData = img.src
				})
			},
			CanvasToImage(canvas) {
				var image = new Image()
				image.src = canvas.toDataURL("image/jpg")
				return image
			},
			onBridgeReady(param) {
				let money = JSON.parse(JSON.stringify(this.money))
				let that = this
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": this.appId, //公众号名称，由商户传入     
						"timeStamp": param.timeStamp, //时间戳，自1970年以来的秒数     
						"nonceStr": param.nonceStr, //随机串     
						"package": param.package,
						"signType": param.signType, //微信签名方式：     
						"paySign": param.paySign //微信签名 
					},
					function(res) {
						// 支付成功
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							uni.navigateTo({
								url: '/pages/success/success?money=' + money + '&type=' + that
									.currenType + '&time=' + formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss') +
									'&orderNo=' + that.orderNo
							})
						} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
							uni.showToast({
								title: '取消支付',
								icon: 'none',
								mask: true
							})
						} else {
							uni.showModal({
								title: '提示',
								content: '调用支付失败 请稍后重试',
								showCancel: false
							})
						}
					});
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		height: 100vh;
		background: url('../../static/bj.png') no-repeat center/100% 100%;
		font-size: 36rpx;

		.pay-bg {
			position: fixed;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			background: url("../../static/bg.png") no-repeat center/75% 75%;
			background-color: rgba(0, 0, 0, .7);
		}

		.box {
			display: flex;
			align-items: center;
			flex-direction: column;

			.text-1 {
				color: #fff;
				line-height: 120rpx;
				margin-bottom: 20rpx;
				font-weight: 500;
			}

			.content {
				box-sizing: border-box;
				background-color: #fff;
				width: 90vw;
				margin: auto;
				height: 73vh;
				border-radius: 48rpx;
				padding: 0 80rpx;
				overflow: hidden;

				.text-2 {
					text-align: center;
					color: rgb(233, 107, 5);
					margin-bottom: 5vh;
					margin-top: 5vh;
					font-weight: 600;
				}

				.input-box {
					display: flex;
					justify-content: center;

					view {
						width: 70%;
						border-bottom: 1rpx solid rgba(0, 0, 0, .1);
						padding-bottom: 20rpx;
						display: flex;

						.text-3 {
							margin: 0 20rpx;
							font-size: 62rpx;
						}

						.input {
							font-size: 60rpx;
							font-weight: 600;
						}
					}
				}

				.text-4 {
					margin-top: 5vh;
					color: #666666;
					font-size: 32rpx;
				}

				.img-box {
					display: flex;
					justify-content: space-between;
					margin-top: 40rpx;

					.item {
						box-sizing: border-box;
						border: 1rpx solid rgba(0, 0, 0, .1);
						width: 45%;
						border-radius: 15rpx;
						text-align: center;
						padding: 30rpx;

						image {
							width: 100rpx;
							height: 100rpx;
						}
					}

					.item-active {
						border: 2rpx solid rgb(232, 117, 8);
						box-shadow: 0 0 10rpx 5rpx rgba(232, 117, 8, .5);
					}

					.text-5 {
						color: rgba(0, 0, 0, .3);
						margin-top: 3vh;
						font-size: 32rpx;
					}
				}

				.text-6 {
					text-align: center;
					background: linear-gradient(113deg, #FD6C03 0%, #FC4F00 100%);
					;
					border-radius: 40rpx;
					line-height: 100rpx;
					margin-top: 8vh;
					color: #fff;
					font-weight: 550;
				}
			}
		}

		.loading {
			width: 80vw;
			background-color: #fff;
			border-radius: 50rpx;
			text-align: center;
			padding: 70rpx 0;
			position: relative;

			.close {
				position: absolute;
				top: 20rpx;
				right: 20rpx;
				width: 48rpx;
				height: 48rpx;
			}

			.text-7 {
				font-weight: 400;
				font-size: 60rpx;
				color: #E86F06;
				margin: 30rpx 0;
			}

			.text-8 {
				font-weight: 400;
				font-size: 36rpx;
				color: #666666;
			}
		}

		.qrCode {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			width: 500rpx;
			height: 500rpx;
			border-radius: 10rpx;
			background-color: #fff;
		}
	}
</style>